<template>
  <div>
    <h1>{{ title }}</h1>
    <hr />
    <input type="text" v-model="keyWords" />
    <h3>{{ keyWords }}</h3>
  </div>
</template>

<script>
import { customRef, ref } from "vue";
export default {
  name: "Demo",
  setup() {
    let title = ref("自定义customRef");

    //customRef: 创建一个自定义的 ref，并对其依赖项跟踪和更新触发进行显式控制。

    //防抖案例
    function toRef(value, delay) {
      let timer;
      return customRef((truck, trigger) => {
        return {
          get() {
            truck(); //追踪Vue模版变化
            return value;
          },
          set(newValue) {
            clearTimeout(timer);
            timer = setTimeout(() => {
              value = newValue;
              trigger(); //通知Vue去重新解析模板
            }, delay);
          },
        };
      });
    }

    let keyWords = toRef("hello", 500); //使用自定义的Ref

    return {
      title,
      keyWords,
    };
  },
};
</script>